var mongoose = require('mongoose');

// Creates connection, the 'mongoose' object knows it's open.
mongoose.connect('mongodb://localhost/test');

var db = mongoose.connection;

// has to be a function
db.on('error', function () {console.log('ERROR!!!');});
// The line below works:
//db.on('error', console.error.bind(console, 'connection error:'));
// But 'console.log('ERROR!!')' does not.

db.once('open', function callack() {
    console.log('It probably works!');

    // Schema is like 'table'?
    var testSchema = mongoose.Schema({
        textField: String
    });
    
    // 'Schema':s can have methods:
    testSchema.methods.functionCall = function() {
        this.textField += this.textField;
        console.log(this.textField);
    }

    // methods can take arguments
    testSchema.methods.functionCallWithArgs = function(data) {
        this.textField += data;
        console.log(this.textField);
    }

    // TestModel is an interface to the schema??
    var TestModel = mongoose.model('TestModel', testSchema);

    // Creating a new 'document' 
    // (the instances of 'Schema' are called 'documents')
    var testDocument = new TestModel({textField: 'content'});
    console.log(testDocument.textField); // It works as expected
    testDocument.functionCall(); // Works as expected
    testDocument.functionCallWithArgs('an arg'); // Works as expected
    
    // Save to database:
    testDocument.save(
        function (err, obj) { // 2:nd argument is the object saved
            if (err) 
                console.log('Error saving testDocument');
            else 
                console.log('Succesfully saved testDocument');
        });

    // Retrieve every one:
    TestModel.find(
        function (err, result) {
            if (err) console.log('Error listing TestModel:s');
            else console.log(result);
        });

    // MongoDB has fancy features: you can search
    // for regexps
    TestModel.find(
        {textField: /^cont/}, function(err, result) {
            console.log(result);});
    
});
